package com.sia.springcloud.heartProtect;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: Sirius
 * @Date: 2021/12/30 15:37
 * @Description: 心跳自启动
 **/
@Slf4j
//@Component
public class HeartbeatRunner implements ApplicationRunner {

    private static final String heartbeatId = "Protocol-Core-HeartbeatProtect";

    //心跳保护频率
    @Value("${heartbeatProtect.frequency:20}")
    private Integer frequency;

    @Resource
    private Scheduler scheduler;


    /**
     * 这是超时处理机制，自动开启，定时清理一些死掉的协议微服务
     * <p>
     * 包含一个心跳保护机制，需要手动开启
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("心跳保护：开启");

        JobKey jobKey = JobKey.jobKey(heartbeatId);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }

        JobDetail jobDetail = JobBuilder.newJob(HeartbeatHandler.class)
                .withIdentity(heartbeatId)
                .storeDurably()
                .build();


        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        scheduleBuilder.repeatForever();
        scheduleBuilder.withIntervalInSeconds(frequency);
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(heartbeatId)
                .withSchedule(scheduleBuilder)
                .startNow()
                .build();


        scheduler.scheduleJob(jobDetail, trigger);


    }
}

